﻿using Pay.DTO;
using Pay.IService;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using Pay.Service;
using System.Threading.Tasks;
using Flurl.Http;
using Pay.Core;
using System.Data;

namespace Pay.Distribution.Controllers {

    public class OrderController : GeneralController {
        private IOrderService _iOrderService;
        private IProductService _iProductService;
        private ILogisticsService _logisticsService;
        private ILogisticsDetailsService _logisticsDetailsService;
        private ILogisticsNOService _iLogisticsNOService;
        private IPayInfoService _payInfoService;
        public OrderController(IOrderService iOrderService, ILogisticsService logisticsService,
            ILogisticsDetailsService logisticsDetailsService, IPayInfoService payInfoService,
            ILogisticsNOService iLogisticsNOService, IProductService iProductService) {
            _iOrderService = iOrderService;
            _logisticsService = logisticsService;
            _logisticsDetailsService = logisticsDetailsService;
            _payInfoService = payInfoService;
            _iLogisticsNOService = iLogisticsNOService;
            _iProductService = iProductService;
        }

        public JsonResult Gets(OrderQuery query) {
            query.merchant_id = currentUser.user_id;
            query.shop_id = currentUser.user_id;
            query.distribution_id = currentUser.user_id;
            var model = _iOrderService.Get(query);
            //var model = _payInfoService.Get(query);
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetOrders(OrderQuery query) {
            query.merchant_id = currentUser.user_id;
            var model = _iOrderService.Get(query);
            return Json(ResultToJson.Json(model), JsonRequestBehavior.AllowGet);
        }

        public JsonResult Get(long id) {
            var orderdetail = new OrderDetail();
            var model = _iOrderService.Get(id);
            orderdetail.order = model;
            //获取物流追踪
            if (model.status == OrderStatus.WaitDelivery)
                orderdetail.list = new List<logistics_details_dto>();
            else
                orderdetail.list = _logisticsDetailsService.GetDeteil(model.id);
            return Json(ResultToJson.Json(orderdetail), JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetLogisticsNO() {
            LogiticsNOQuery query = new LogiticsNOQuery() { logiticsstatus = 1 };
            var logistics_no = _iLogisticsNOService.Gets(query);
            return Json(ResultToJson.Json(logistics_no), JsonRequestBehavior.AllowGet);
        }

        //public JsonResult SaveShipping(order_shipping_ex dto) {
        //    var result = _iOrderService.OrderDelivery(dto);
        //    return Json(ResultToJson.Json(result >= 0 ? "发货成功" : "发货失败"), JsonRequestBehavior.AllowGet);
        //}

        public JsonResult OrderDelivery(long id) {
            var result = _iOrderService.OrderDelivery(id);
            return Json(ResultToJson.Json(result >= 0 ? "发货成功" : "发货失败"), JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 发货
        /// </summary>
        /// <returns>The save.</returns>
        /// <param name="order">Order.</param>
        public JsonResult Shipping(order_dto_ex order) {
            var result = _iOrderService.OrderDelivery(order);
            return Json(ResultToJson.Json(result > 0 ? "发货成功" : "发货失败", result), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 确认收货
        /// </summary>
        /// <returns></returns>
        public JsonResult Recipient(long id) {
            var result = _iOrderService.HandConfirmOrder(id);
            if (result > 0)
                return Json(ResultToJson.Json("确认收货成功", "确认收货成功"));
            else
                return Json(ResultToJson.Json("确认收货失败"));
        }
        public JsonResult Stop(long id) {
            var result = _iOrderService.StopAutoOrder(id);
            if (result > 0)
                return Json(ResultToJson.Json("停止成功", "停止成功"));
            else
                return Json(ResultToJson.Json("停止失败"));
        }
        /// <summary>
        /// 推单
        /// </summary>
        /// <param name="order_no"></param>
        /// <returns></returns>
        public async Task<JsonResult> Push(string order_no) {
            string result = string.Empty;
            string api_url = t_RequestMethod.dis_api_url;
            var order = _iOrderService.Get(order_no);
            if (order.order_type.HasValue) {
                if (order.order_type.Value == 1) {
                    api_url = string.Format(api_url, "htl_batch_push_order", order_no);
                } else if (order.order_type.Value == 2) {
                    api_url = string.Format(api_url, "hniao_batch_push_order", order_no);
                }
                try {
                    result = await api_url.GetAsync().ReceiveString();
                }
                catch {

                }
            }
            if (result == "1")
                return Json(ResultToJson.JsonAsync("推送成功", "推送成功"));
            else
                return Json(ResultToJson.JsonAsync<string>("推送失败"));
        }
        /// <summary>
        /// 修改收货人信息
        /// </summary>
        /// <returns></returns>
        public JsonResult SaveInfo(shipping_address_dto dto) {
            int result = _iOrderService.OrderShiping(dto);
            if (result > 0)
                return Json(ResultToJson.Json("保存成功"));
            else
                return Json(ResultToJson.Json<string>("保存失败"));
        }
        public async Task<JsonResult> SearchSku(string sku) {
            var result = await _iProductService.SearchSkuInfo(sku);
            return Json(ResultToJson.Json("查询成功", result));
        }
        /// <summary>
        /// 保存商品sku信息
        /// </summary>
        /// <returns></returns>
        public JsonResult SaveSku(product_sku_info dto) {
            int result = _iProductService.SaveProductSku(dto);
            if (result > 0)
                return Json(ResultToJson.Json("保存成功"));
            else
                return Json(ResultToJson.Json<string>("保存失败"));
        }
        /// <summary>
        /// 修改订单号
        /// </summary>
        /// <param name="order_no"></param>
        /// <param name="new_order_no"></param>
        /// <returns></returns>
        public JsonResult SaveOrder(string order_no, string new_order_no) {
            int result = _iOrderService.SaveOrderNo(order_no, new_order_no);
            if (result > 0)
                return Json(ResultToJson.Json("保存成功", "保存成功"));
            else
                return Json(ResultToJson.Json<string>("保存失败"));
        }
        /// <summary>
        /// 订单导出
        /// </summary>
        /// <returns></returns>
        public FileResult Export(OrderQuery query) {
            //query.merchant_id = currentUser.user_id;
            var result = _iOrderService.Gets(query);

            HSSFWorkbook workbook = new HSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue("商品名称");
            row.CreateCell(1).SetCellValue("下单时间");
            row.CreateCell(2).SetCellValue("订单号");
            row.CreateCell(3).SetCellValue("销售价");
            row.CreateCell(4).SetCellValue("供货价");
            row.CreateCell(5).SetCellValue("姓名");
            row.CreateCell(6).SetCellValue("数量");
            row.CreateCell(7).SetCellValue("总价");
            row.CreateCell(8).SetCellValue("收货人姓名");
            row.CreateCell(9).SetCellValue("收货地址");
            row.CreateCell(10).SetCellValue("手机号");
            row.CreateCell(11).SetCellValue("身份证号");
            sheet.SetColumnWidth(0, 6500);
            sheet.SetColumnWidth(1, 6500);
            sheet.SetColumnWidth(2, 6500);
            sheet.SetColumnWidth(3, 6500);
            sheet.SetColumnWidth(4, 6500);
            sheet.SetColumnWidth(5, 6500);
            sheet.SetColumnWidth(6, 6500);
            sheet.SetColumnWidth(7, 6500);
            sheet.SetColumnWidth(8, 6500);
            sheet.SetColumnWidth(9, 6500);
            sheet.SetColumnWidth(10, 6500);
            sheet.SetColumnWidth(11, 6500);
            for (int i = 0; i < result.Count; i++) {
                foreach (var item in result[i].OrderItems) {
                    IRow row2 = sheet.CreateRow(i + 1);
                    row2.CreateCell(0).SetCellValue(item.ProductName);
                    row2.CreateCell(1).SetCellValue(result[i].OrderTime.ToString());
                    row2.CreateCell(2).SetCellValue(result[i].OrderNo);
                    row2.CreateCell(3).SetCellValue("￥" + item.UnitPrice.ToString());
                    row2.CreateCell(4).SetCellValue("￥" + (item.Product != null ? item.Product.CostPrice.ToString() : "0"));
                    row2.CreateCell(5).SetCellValue(result[i].Buyer != null ? result[i].Buyer.Name : "");
                    row2.CreateCell(6).SetCellValue(item.Quantity);
                    row2.CreateCell(7).SetCellValue(result[i].PayAmount.ToString());
                    row2.CreateCell(8).SetCellValue(result[i].Shipping.ShipTo);
                    row2.CreateCell(9).SetCellValue(result[i].Shipping.RegionName + result[i].Shipping.Address);
                    row2.CreateCell(10).SetCellValue(result[i].Buyer != null ? result[i].Buyer.Mobile : "");
                    row2.CreateCell(11).SetCellValue(result[i].Shipping.IdCard);
                }
            }
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            stream.Seek(0L, SeekOrigin.Begin);
            return this.File(stream, "application/vnd.ms-excel", "商品订单表.xls");
        }
        /// <summary>
        /// 物流追踪
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> AShipping(long order_id) {
            var order_dto = _iOrderService.Get(order_id);
            var result = await _logisticsDetailsService.GetLogisticInfo(order_dto);
            return Json(ResultToJson.Json(result.ToDtoObject<logistic_results_ex>()), JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 导入发货信息
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult ImportDelivery() {
            if (Request.Files.Count == 0)
                throw new ServerErrorException("请选择发货信息文件");
            var file = Request.Files["file"];
            if (file == null)
                throw new ServerErrorException("请选择发货信息文件");
            string ext = Path.GetExtension(file.FileName).ToLower();

            if (ext != ".xls" && ext != ".xlsx")
                throw new ServerErrorException("上传文件格式不正确, 支持xls、xlsx类型的文件");

            using (ExcelHelper excelHelper = new ExcelHelper(file.FileName)) {
                DataTable dt = excelHelper.ExcelToDataTable(file.InputStream, "Sheet1", true);
               var result = _iOrderService.ImportDelivery(dt);
                return Json(ResultToJson.Json( result ? "操作成功" : "操作失败", result), JsonRequestBehavior.AllowGet);
            }
        }
    }
}